package models

import (
	"fmt"
	"strings"
)

type NullType byte

const (
	_ NullType = iota
	// IsNull the same as `is null`
	IsNull
	// IsNotNull the same as `is not null`
	IsNotNull
)

// sql build where
func (model BaseModel) WhereBuild(where map[string]interface{}) (condition string, values []interface{}, err error) {
	for k, v := range where {
		//vj, _ := json.Marshal(v)
		//if len(vj) <= 2 {
		//	continue
		//}
		ks := strings.Split(k, " ")
		if len(ks) > 2 {
			return "", nil, fmt.Errorf("Error in query condition: %s. ", k)
		}

		if condition != "" {
			condition += " AND "
		}
		strings.Join(ks, ",")
		switch len(ks) {
		case 1:
			//fmt.Println(reflect.TypeOf(v))
			switch vt := v.(type) {
			case NullType:
				if vt == IsNotNull {
					condition += fmt.Sprint(k, " IS NOT NULL")
				} else {
					condition += fmt.Sprint(k, " IS NULL")
				}
			default:
				condition += fmt.Sprint(k, "=?")
				values = append(values, v)
			}
			break
		case 2:
			k = ks[0]
			switch ks[1] {
			case "=":
				condition += fmt.Sprint(k, " =?")
				values = append(values, v)
				break
			case ">":
				condition += fmt.Sprint(k, " >?")
				values = append(values, v)
				break
			case ">=":
				condition += fmt.Sprint(k, " >=?")
				values = append(values, v)
				break
			case "<":
				condition += fmt.Sprint(k, " <?")
				values = append(values, v)
				break
			case "<=":
				condition += fmt.Sprint(k, " <=?")
				values = append(values, v)
				break
			case "!=":
				condition += fmt.Sprint(k, " !=?")
				values = append(values, v)
				break
			case "<>":
				condition += fmt.Sprint(k, " !=?")
				values = append(values, v)
				break
			case "in":
				condition += fmt.Sprint(k, " in (?)")
				values = append(values, v)
				break
			case "nin":
				condition += fmt.Sprint(k, " not in (?)")
				values = append(values, v)
				break
			case "like":
				condition += fmt.Sprint(k, " like ?")
				values = append(values, v)
			}
			break
		}
	}
	return
}
